<template>
  <div class="box">
    <div class="header">
      <el-button type="primary" :icon="Plus" solid @click="openDialog">添加网红小店</el-button>
    </div>
    <div class="content">
      <el-table :data="tableData" border style="width: 100%;">
        <el-table-column prop="name" label="名字" width="180" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="url" label="小店图片">
          <template #default="scope">
            <img class="whxd-img" :src="scope.row.url[0]" alt="小店图片">
          </template>
        </el-table-column>
        <el-table-column prop="label" label="小店标签">
          <template #default="scope">
            <el-tag v-for="(item, index) in scope.row.label" :key="index" type="warning">{{ item }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="businessHours" label="营业时间"/>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="success" :icon="Edit" @click="openDialog('edit', scope.row)">修改</el-button>
            <el-button type="danger" :icon="Delete" @click="deleteItem(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="whxdVisible" :title="dialogType === 'add' ? '新增网红小店' : '编辑网红小店'" width="500" center>
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" label-width="auto">
        <el-form-item label="店铺名称" prop="name">
          <el-input v-model="ruleForm.name"/>
        </el-form-item>
        <el-form-item label="店铺地址" prop="address">
          <el-input v-model="ruleForm.address" type="textarea" />
        </el-form-item>
        <el-form-item label="营业时间" prop="businessHours">
          <el-time-select v-model="ruleForm.startTime" style="width: 140px" :max-time="ruleForm.endTime"
            placeholder="开始时间" start="00:00" step="00:30" end="23:59" />
          <el-time-select v-model="ruleForm.endTime" style="width: 140px" :min-time="ruleForm.startTime"
            placeholder="结束时间" start="00:00" step="00:30" end="23:59" />
        </el-form-item>
        <el-form-item label="店铺标签" prop="label">
          <el-input-tag v-model="ruleForm.label" placeholder="请输入标签" aria-label="请输入后敲击回车" />
        </el-form-item>
        <el-form-item label="店铺介绍" prop="remark">
          <el-input v-model="ruleForm.remark" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { Delete, Edit, Plus } from '@element-plus/icons-vue'
import data from '@/utils/data';
import { onMounted, ref } from 'vue';

const tableData = ref([]);
const whxdVisible = ref(false);
const ruleFormRef = ref()
const dialogType = ref('add')
const whxdId = ref(null)

const ruleForm = ref({ 
  name: '',
  address: '',
  startTime: '',
  endTime: '',
  urlList: [],
  label: [],
  remark: ''
})

const openDialog = (type, row) => {
  ruleForm.value = { 
    name: '',
    address: '',
    startTime: '',
    endTime: '',
    urlList: [],
    label: [],
    remark: ''
  }
  
  whxdVisible.value = true;
  
  if (type === 'edit' && row) {
    dialogType.value = 'edit'
    ruleForm.value = { ...row }
    
    // 兼容处理营业时间格式
    const hours = row.businessHours || ''
    const [start, end] = hours.split(' - ')
    ruleForm.value.startTime = start || ''
    ruleForm.value.endTime = end || ''
    
    // 兼容图片字段
    if (!ruleForm.value.urlList) {
      ruleForm.value.urlList = Array.isArray(row.url) ? [...row.url] : []
    }
    
    whxdId.value = row.id
  } else {
    dialogType.value = 'add'
    whxdId.value = null
  }
}

onMounted(() => {
  const savedData = localStorage.getItem('whxdData')
  if (savedData) {
    tableData.value = JSON.parse(savedData)
  } else {
    tableData.value = data.map((item, index) => ({
      id: index + 1,
      ...item
    }))
    localStorage.setItem('whxdData', JSON.stringify(tableData.value))
  }
})

const deleteItem = (index) => {
  tableData.value.splice(index, 1)
  localStorage.setItem('whxdData', JSON.stringify(tableData.value))
}

const submitForm = async (formEl) => {
  if (!formEl) return

  await formEl.validate((valid, fields) => {
    if (valid) {
      const businessHours = `${ruleForm.value.startTime || ''} - ${ruleForm.value.endTime || ''}`
      
      if (whxdId.value) {
        const index = tableData.value.findIndex(item => item.id === whxdId.value)
        if (index !== -1) {
          tableData.value[index] = {
            id: whxdId.value,
            name: ruleForm.value.name,
            address: ruleForm.value.address,
            businessHours,
            url: Array.isArray(ruleForm.value.urlList) ? [...ruleForm.value.urlList] : [],
            label: Array.isArray(ruleForm.value.label) ? [...ruleForm.value.label] : [],
            remark: ruleForm.value.remark || ''
          }
        }
      } else {
        const maxId = tableData.value.length > 0
          ? Math.max(...tableData.value.map(item => item.id || 0))
          : 0
          
        tableData.value.push({
          id: maxId + 1,
          name: ruleForm.value.name,
          address: ruleForm.value.address,
          businessHours,
          url: Array.isArray(ruleForm.value.urlList) ? [...ruleForm.value.urlList] : [],
          label: Array.isArray(ruleForm.value.label) ? [...ruleForm.value.label] : [],
          remark: ruleForm.value.remark || ''
        })
      }
      
      localStorage.setItem('whxdData', JSON.stringify(tableData.value))
      
      ruleForm.value = {
        name: '',
        address: '',
        startTime: '',
        endTime: '',
        urlList: [],
        label: [],
        remark: ''
      }
      
      whxdVisible.value = false
    } else {
      console.log('error submit!', fields);
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped lang="scss">
.box {
  padding: 20px;

  .header {
    display: flex;
    justify-content: flex-end;
  }

  .content {
    margin-top: 20px;

    .whxd-img {
      width: 100px;
      height: 100px;
      object-fit: cover;
    }
  }
}
</style>